
package com.vanda.db.util;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;

import com.vanda.db.exception.MappingException;

/**
 * JavaBean反射工具类<br>
 * 
 * @author 王瑛<br>
 * @version Version 1.00<br>
 */
public class BeanUtils {
	/** 保存类与方法集合对应关系 */
	private static HashMap _fieldInfo = new HashMap();
	
	/**
	 * 取对象的反射信息
	 * @param dataClass JavaBean的class类
	 * @param isSet true-只取set方法，false-只取get方法
	 * @return 
	 * @throws Exception
	 */
	public static HashMap getFieldInfo(Class dataClass, boolean isSet)
		throws Exception {
		String key = dataClass.getName() + isSet;
		HashMap hmField = (HashMap) _fieldInfo.get(key);
		if (hmField == null) {
			hmField = getFieldMethod(dataClass, isSet);
			_fieldInfo.put(key, hmField);
		}
		return hmField;
	}
	
	/**
	 * 取得对象的方法信息
	 * @param drbean
	 * @param isSet
	 * @return
	 * @throws Exception
	 */
	private static HashMap getFieldMethod(Class drbean, boolean isSet)
		throws Exception {
		try {
			Class stopClass = null;
			BeanInfo drbeanInfo = null;
			//stopClass = drbean.getSuperclass();
			//不要检查Object方法类型
			stopClass = Object.class;
			drbeanInfo = Introspector.getBeanInfo(drbean, stopClass);
			PropertyDescriptor[] props;
			HashMap hm = new HashMap();
			props = drbeanInfo.getPropertyDescriptors();
			for (int i = 0; i < props.length; i++) {
				Method method = null;
				if (isSet) {
					method = props[i].getWriteMethod();
				} else {
					method = props[i].getReadMethod();
				}
				if (method != null) {
					String field = props[i].getName().toLowerCase();
					hm.put(field, method);
				}
			}
			return hm;
		} catch (IntrospectionException e) {
			e.printStackTrace();
			throw new MappingException("Get Bean Field Failed!", e);
		}
	}
}
